﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.Notify;
using ManagementApi.Models.System.TableLog;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.BankSpecialAccount;
using Modules.Notify;
using Modules.Person;
using Modules.Project;
using Modules.Reports;
using PmSoft.Logging;

namespace ManagementApi.Controllers.CommanderPannel;

/// <summary>
/// 首页统计信息接口-项目管理员角色
/// </summary>
[ApiController]
[Route("/api/v1/commander/home")]
[Authorize(Roles = "Commander")]
public class HomeController
{
    private readonly ProjectCommanderApplicationContext applicationContext;
    private readonly ILogger logger;
    private readonly ProjectService projectService;
    private readonly SysNotifyService sysNotifyService;
    private readonly SysTableLogService sysTableLogService;
    private readonly IMapper mapper;
    private readonly ProjectGroupMemberService projectGroupMemberService;
    private readonly PersonService personService;
    private readonly PersonCorpContractService personCorpContractService;
    private readonly ReportProjectGroupDaysService reportProjectGroupDaysService;
    private readonly BankSpecialAccountService bankSpecialAccountService;
    private readonly BankSpecialAccountStatisticService bankSpecialAccountStatisticService;
    private readonly ProjectGuaranteePaymentService projectGuaranteePaymentService;
    private readonly ReportProjectMonthService reportProjectMonthService;

    /// <summary>
    /// </summary>
    /// <param name="applicationContext"></param>
    /// <param name="logger"></param>
    /// <param name="projectService"></param>
    /// <param name="sysNotifyService"></param>
    /// <param name="sysTableLogService"></param>
    public HomeController(ProjectCommanderApplicationContext applicationContext, ILogger<HomeController> logger, ProjectService projectService,
        SysNotifyService sysNotifyService, SysTableLogService sysTableLogService, IMapper mapper, ProjectGroupMemberService projectGroupMemberService, PersonService personService, PersonCorpContractService personCorpContractService, ReportProjectGroupDaysService reportProjectGroupDaysService, BankSpecialAccountService bankSpecialAccountService, BankSpecialAccountStatisticService bankSpecialAccountStatisticService, ProjectGuaranteePaymentService projectGuaranteePaymentService, ReportProjectMonthService reportProjectMonthService)
    {
        this.applicationContext = applicationContext;
        this.logger = logger;
        this.projectService = projectService;
        this.sysNotifyService = sysNotifyService;
        this.sysTableLogService = sysTableLogService;
        this.mapper = mapper;
        this.projectGroupMemberService = projectGroupMemberService;
        this.personService = personService;
        this.personCorpContractService = personCorpContractService;
        this.reportProjectGroupDaysService = reportProjectGroupDaysService;
        this.bankSpecialAccountService = bankSpecialAccountService;
        this.bankSpecialAccountStatisticService = bankSpecialAccountStatisticService;
        this.projectGuaranteePaymentService = projectGuaranteePaymentService;
        this.reportProjectMonthService = reportProjectMonthService;
    }

    /// <summary>
    /// 首页统计
    /// </summary>
    /// <returns></returns>
    [HttpGet("home_statistic")]
    public ApiResult<HomeStatisticDto> GetHomeStatistic()
    {
        var statistic = projectService.GetHomeStatistic();
        return ApiResult<HomeStatisticDto>.Success(statistic.AsDto(applicationContext));
        var projectIds = projectService.GetAllProjectIdsByApplicationContext();
        var dto = new HomeStatisticDto();
        if (!projectIds.Any()) return ApiResult<HomeStatisticDto>.Success(dto);
        var members = projectGroupMemberService.GetProjectGroupMembersByProjectIds(projectIds);
        var persons = personService.GetPersons(members.Select(i => i.PersonId));
        var contracts = personCorpContractService.GetPersonCorpContractsByPersonIds(members.Select(i => i.PersonId));
        var reportDays = reportProjectGroupDaysService.GetReportProjectDays(new ReportProjectGroupDaysQuery()
        {
            ProjectIds = projectIds,
            StartTime = DateTime.Now.AddDays(-1),
            EndTime = DateTime.Now.AddDays(-1),
        });
        var accounts = bankSpecialAccountService.GetProjectSpecialAccountByProjectIds(projectIds);
        var statistics = bankSpecialAccountStatisticService.GetProjectSpecialAccountStatistics(accounts.Select(i => i.BankNo));
        var guarantees = projectGuaranteePaymentService.GetProjectGuaranteePaymentsByProjectIds(projectIds);

        dto.ManagerCount = members.Count(i => i.IsManager);
        dto.SuperviseCount = members.Count(i => i.IsManager && i.PostCategory == PersonConstants.管理岗位类型.总监理工程师);
        dto.PersonCount = persons.Count();
        dto.PersonXZCount = persons.Count(i => i.Nation == "藏");
        dto.SignPersonCount = contracts.GroupBy(i => i.PersonId).Count();
        dto.ContractCount = contracts.Count();
        if (dto.PersonCount > 0)
        {
            dto.PersonXZRatio = ((Convert.ToDecimal(dto.PersonXZCount) / Convert.ToDecimal(dto.PersonCount)) * 100).ToString("0.00");
            dto.SignContractRatio = ((Convert.ToDecimal(dto.SignPersonCount) / Convert.ToDecimal(dto.PersonCount)) * 100).ToString("0.00");
        }
        dto.NumberAttendees = reportDays.Sum(i => i.NumberAttendees);
        dto.ActualAttendance = reportDays.Sum((i) => i.ActualAttendance);
        dto.BankAccountBalance = accounts.Sum(i => i.Balance ?? 0);
        dto.IncomeAmount = statistics.Sum(i => i.IncomeAmount);
        dto.OnlinePaymentAmount = statistics.Sum(i => i.OnlinePaymentAmount);
        dto.OfflinePaymentAmount = statistics.Sum(i => i.OfflinePaymentAmount);
        dto.GuaranteeBalance = guarantees.Sum(i => i.Balance);
        dto.PaymentPersonCount = 0;// reportProjectMonthService.GetReportProjectMonthByProjectIds(projectIds).Sum(i => i.NumberProxyRecipients);
        if (dto.NumberAttendees > 0)
        {
            dto.AttendanceRatio = ((Convert.ToDecimal(dto.ActualAttendance) / Convert.ToDecimal(dto.NumberAttendees)) * 100).ToString("0.00");
        }
        dto.AbsenceAttendance = dto.NumberAttendees - dto.ActualAttendance;
        dto.TotalPaymentAmount = dto.OfflinePaymentAmount + dto.OnlinePaymentAmount;
        dto.Notifys = sysNotifyService.GetSysNotifysByPage(new NotifyQuery(), 1, 10).AsSysNotifyDtos();
        dto.TableLog = sysTableLogService.GetLogs(new SysTableLogQuery(), 1, 10).AsDtos();
        return ApiResult<HomeStatisticDto>.Success(dto);
    }
}